package com.fotkidemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.fotkidemo.beans.Album;
import com.fotkidemo.network.json.AbstractJsonEntryParser;
import com.fotkidemo.network.json.JsonAlbumsParser;
import com.fotkidemo.tasks.DownloadAndParseEntryTask;
import com.fotkidemo.util.BitmapCache;
import com.fotkidemo.util.DiskCache;
import com.fotkidemo.util.ImageDownloader;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: roma
 * Date: 6/24/12
 * Time: 12:47 AM
 * To change this template use File | Settings | File Templates.
 */

/**
 * Отображение списка альбомов пользователя на yandex фотка в отдельном фрагменте.
 */
public class AlbumsFragment extends Fragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "AlbumsFragment";
    private static final String IMAGE_URL = "image_url";

    private OnAlbumsClickListener listener;
    private LayoutInflater inflater;

    private String URL;

    /**
     * Фрагмент связывается с activity через данный интерфейс.
     * При это в activity динамически создается меню для списка альбомов
     */
    public interface OnAlbumsClickListener {
        public void onAlbumClick(int position, Album album, AdapterView<?> adapterView);
        public void onCreateMenu(Menu menu);
        public boolean onMenuItemSelected(MenuItem item);
    }

    public static AlbumsFragment newInstance(String url) {
        final AlbumsFragment f = new AlbumsFragment();

        final Bundle args = new Bundle();
        args.putString(IMAGE_URL, url);
        f.setArguments(args);

        return f;
    }

    public AlbumsFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        URL = getArguments() != null ? getArguments().getString(IMAGE_URL) : "";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        final View v = inflater.inflate(R.layout.albums, container, false);
        final ListView listView = (ListView) v.findViewById(R.id.titles);

        if (BuildConfig.DEBUG)
            Log.d(TAG, new StringBuilder("Get json albums from url= ").append(URL).toString());

        //Получить информацию о альбомах пользователя
        new DownloadAndPArseAlbumsTask(listView).execute(URL);

        listView.setOnItemClickListener(this);

        registerForContextMenu(listView);

        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            listener = (OnAlbumsClickListener) activity;
        } catch (ClassCastException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Album album = (Album) adapterView.getItemAtPosition(i);

        listener.onAlbumClick(i, album, adapterView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        listener.onCreateMenu(menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
//        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        return listener.onMenuItemSelected(item);
    }

    //Асинхронное выполнение запроса на альбомы пользователя
    private class DownloadAndPArseAlbumsTask extends DownloadAndParseEntryTask<Album> {
        private ListView view;

        private DownloadAndPArseAlbumsTask(ListView view) {
            this.view = view;
        }

        @Override
        public void onCompleteTask(List<Album> entries) {
            if (BuildConfig.DEBUG)
                Log.d(TAG, "set albums adapter");

//            ListAdapter adapter =
//                    new ArrayAdapter<Album>(getActivity(), R.layout.list_item, entries);
            AlbumsAdapter adapter = new AlbumsAdapter(entries);
            view.setAdapter(adapter);
        }

        @Override
        public String getTag() {
            return TAG;
        }

        @Override
        public AbstractJsonEntryParser getJsonParser(String json) {
            return new JsonAlbumsParser(json);
        }
    }

    private class AlbumsAdapter extends BaseAdapter {
        private List<Album> albums;

        private AlbumsAdapter(List<Album> albums) {
            this.albums = albums;
        }

        @Override
        public int getCount() {
            return albums.size();
        }

        @Override
        public Object getItem(int i) {
            return albums.get(i);
        }

        @Override
        public long getItemId(int i) {
            return albums.get(i).getId().hashCode();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            if (view == null) {
                view = inflater.inflate(R.layout.list_item, null);
            }

            TextView text = (TextView)view.findViewById(R.id.item_text);
            text.setText(albums.get(i).getTitle());
            ImageView imageView = (ImageView) view.findViewById(R.id.item_image);
            imageView.setImageResource(R.drawable.empty_photo);
            if (albums.get(i).getHrefXXS() != null) {
                if(BuildConfig.DEBUG)
                    Log.d(TAG, "set image for imageView in albums");

                DiskCache diskCache = DiskCache.initAndCreate(getActivity(), "albums");
                ImageDownloader imageDownloader = new ImageDownloader(null);
                BitmapCache cache = BitmapCache.getInstance();
                Bitmap bitmap = cache.get(albums.get(i).getHrefXXS());
                if (bitmap != null) {
                    if (BuildConfig.DEBUG)
                        Log.d(TAG, "image found in bitmap cache");

                    imageView.setImageBitmap(bitmap);
                } else {
                    imageDownloader.download(albums.get(i).getHrefXXS(), imageView, diskCache);
                }
            }
            return view;
        }
    }
}
